﻿using System;
using System.Linq;
using System.Threading.Tasks;
using JT.Data;
using JT.Domain;
using JT.WEB;
using JT.WEB.Views;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace JTWEB3.Controllers
{
    [Authorize(Roles = "ChaWu")]

    public class CaiWuController : Controller
    {
        private readonly ContextBase _context;
        public CaiWuController(ContextBase context)
        {
            _context = context;
        }
        // GET: CaiWus
        public async Task<IActionResult> Index(
            string sortOrder,
            string currentFilter,
            int? pageNumber,
            string searchString)
        {
            ViewData["CurrentSort"] = sortOrder;
            ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "Name";
            ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
            ViewData["IdSortParm"] = sortOrder == "Id" ? "Id_desc" : "Id";
            if (searchString != null)
            {
                pageNumber = 1;
            }
            else
            {
                searchString = currentFilter;
            }
            IQueryable<Summary> zhaiYaos = from s in _context.Summaries
                                           select s;
            if (!String.IsNullOrEmpty(searchString))
            {
                zhaiYaos = zhaiYaos.Where(s =>
                   s.SummaryName.Contains(searchString) |
                   s.Id.ToString().Contains(searchString)
                );
            }
            switch (sortOrder)
            {
                case "name_desc":
                    zhaiYaos = zhaiYaos.OrderByDescending(s => s.SummaryName);
                    break;
                case "Name":
                    zhaiYaos = zhaiYaos.OrderBy(s => s.SummaryName);
                    break;
                case "Id":
                    zhaiYaos = zhaiYaos.OrderBy(s => s.Id);
                    break;
                default:
                    zhaiYaos = zhaiYaos.OrderByDescending(s => s.Id);
                    break;
            }
            int pageSize = 3;

            return View(await PaginatedList<Summary>.CreateAsync(zhaiYaos.AsNoTracking(), pageNumber ?? 1, pageSize));
        }
        // GET: CaiWu/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            Summary cZhaiYao = await _context.Summaries
                .FirstOrDefaultAsync(m => m.Id == id).ConfigureAwait(false);
            if (cZhaiYao == null)
            {
                return NotFound();
            }
            return View(cZhaiYao);
        }
        // GET: CaiWu/Create
        public IActionResult Create()
        {
            return View();
        }
        // POST: CaiWu/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(GeneralLedger vm)
        {
            if (ModelState.IsValid)
            {
                vm.Footing = (vm.CreditAmount ?? 0) + (vm.DebitAmount ?? 0);

                _context.Add(vm);
                await _context.SaveChangesAsync();

                //return View(nameof(AddZongZhang), zongzhang);
                return RedirectToAction(nameof(Index), controllerName: "CZongZhangs", new { vm.SummaryId });
            }
            return View(vm);
        }

        [HttpGet]
        public IActionResult AddZongZhang(int? id, GeneralLedger vm)
        {
            //var cZhaiYao = await _context.ZhaiYaos
            //    .FirstOrDefaultAsync(m => m.Id == id);
            //if (cZhaiYao == null)
            //{
            //    return NotFound();
            //}
            //var vm = new CZongZhang { CZhaiYaos = cZhaiYao };
            //if (vm.ZhaiYaoName==null &&ZhaiYaoId!=0 && ZhaiYaoName!=null)
            //{
            //    vm.ZhaiYaoId = ZhaiYaoId;
            //    vm.ZhaiYaoName = ZhaiYaoName;
            //    return View(vm);
            //}
            return View(vm);
        }

        [HttpPost]
        public async Task<IActionResult> AddZongZhang(GeneralLedger vm)
        {
            if (ModelState.IsValid)
            {
                vm.Footing = (vm.DebitAmount ?? 0) + (vm.CreditAmount ?? 0);
                if (vm.Footing == 0)
                {
                    ModelState.AddModelError(string.Empty, "保存失败,借方金额和贷方金额不能同时为空");
                    return View(vm);
                }
                Summary zhaiYao = await _context.Summaries.FindAsync(vm.SummaryId);
                zhaiYao.GeneralLedgers.Add(vm);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index), controllerName: "CZongZhangs", zhaiYao);
                //return View(nameof(ZhaiYaoManage), vm.ZhaiYaoId);
            }
            return View(vm);
        }
        public IActionResult ZhaiYaoManage(int Id)
        {
            if (Id == 0)
            {
                return NotFound();
            }
            IQueryable<GeneralLedger> vm = from s in _context.GeneralLedgers
                                           select s;
            vm = vm.Where(s =>
               s.Id == Id);
            return View(vm);
        }
        // GET: CaiWu/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            Summary cZhaiYao = await _context.Summaries.FindAsync(id);
            if (cZhaiYao == null)
            {
                return NotFound();
            }
            return View(cZhaiYao);
        }
        // POST: CaiWu/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, Summary cZhaiYao)
        {
            if (id != cZhaiYao.Id)
            {
                return NotFound();
            }
            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(cZhaiYao);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CZhaiYaoExists(cZhaiYao.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(cZhaiYao);
        }
        public async Task<IActionResult> ZongZhangEdit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            GeneralLedger zongZhang = await _context.GeneralLedgers.FindAsync(id);
            if (zongZhang == null)
            {
                return NotFound();
            }
            return View(zongZhang);
        }

        [HttpPost]
        public async Task<IActionResult> ZongZhangEdit(int? id, GeneralLedger vm)
        {
            if (id != vm.Id)
            {
                return NotFound();
            }
            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(vm);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CZongZhangExists(vm.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(ZhaiYaoManage), new { id = vm.SummaryId });
            }
            return View(vm);
        }
        public async Task<IActionResult> DetailZongZhang(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            GeneralLedger zongZhang = await _context.GeneralLedgers
                .FirstOrDefaultAsync(m => m.Id == id);
            if (zongZhang == null)
            {
                return NotFound();
            }
            return View(zongZhang);
        }
        // GET: CaiWu/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            Summary cZhaiYao = await _context.Summaries
                .FirstOrDefaultAsync(m => m.Id == id);
            if (cZhaiYao == null)
            {
                return NotFound();
            }
            return View(cZhaiYao);
        }
        public async Task<IActionResult> DeleteAll(int id)
        {
            System.Collections.Generic.List<Summary> vm = await _context.Summaries.ToListAsync();
            foreach (Summary item in vm)
            {
                _context.Summaries.Remove(item);
            }
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        // POST: CaiWu/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {

            IQueryable<GeneralLedger> vm = from s in _context.GeneralLedgers
                                           select s;
            vm = vm.Where(s =>
               s.SummaryId == id);
            _context.GeneralLedgers.RemoveRange(vm);
            Summary cZhaiYao = await _context.Summaries.FindAsync(id);
            _context.Summaries.Remove(cZhaiYao);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        private bool CZhaiYaoExists(int id)
        {
            return _context.Summaries.Any(e => e.Id == id);
        }
        private bool CZongZhangExists(int id)
        {
            return _context.GeneralLedgers.Any(e => e.Id == id);
        }

    }
}
